package com.capgemini.fs.presentation.forum.web.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.capgemini.fs.app.ekms.common.Constants;
import com.capgemini.fs.app.ekms.model.Reply;
import com.capgemini.fs.app.ekms.model.Topic;
import com.capgemini.fs.app.ekms.model.User;
import com.capgemini.fs.app.ekms.service.ReplyService;
import com.capgemini.fs.app.ekms.service.TopicService;
import com.capgemini.fs.app.ekms.service.UserService;
import com.capgemini.fs.presentation.forum.web.form.ShowTopicDetailsForm;

public class ShowTopicDetailsAction extends DispatchAction {
	TopicService topicService = null;
	UserService userService = null;
	ReplyService replyService = null;
	int pageSize = 10;

	public TopicService getTopicService() {
		return topicService;
	}

	public void setTopicService(TopicService topicService) {
		this.topicService = topicService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ReplyService getReplyService() {
		return replyService;
	}

	public void setReplyService(ReplyService replyService) {
		this.replyService = replyService;
	}

	// Sort Reply list
	public List<Reply> sortReplyList(List<Reply> list) {

		// Compare reply by lastUpdateDate
		Comparator<Reply> compareByLastCreateDate = new Comparator<Reply>() {
			public int compare(Reply r1, Reply r2) {
				return r1.getLastUpdateDate().compareTo(r2.getLastUpdateDate());
			}
		};
		Collections.sort(list, compareByLastCreateDate);
		return list;
	}

	// List all replies to current topic
	public ActionForward listReply(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int topicId = 0;
		//show topic details which is created before
		if (null != request.getParameter("topicId")) {
			topicId = Integer.valueOf(request.getParameter("topicId"));
		}
		//show topic details which is just created, the topic id is set in request attribute
		if (null != request.getAttribute("topicId")) {
			topicId = Integer.valueOf(request.getAttribute("topicId")
					.toString());
		}
		Topic topic = topicService.getTopicById(topicId);
		Integer newViewsCount=topic.getViewsCount()+1;
		topic.setViewsCount(newViewsCount);
		// This list stored all the topics queried from database
		Set<Reply> replySet = topic.getReplies();
		List<Reply> replyList = new ArrayList<Reply>();
		for (Reply reply : replySet) {
			replyList.add(reply);
		}
		List<Reply> repliesOnCurrentPage = new ArrayList<Reply>();
		sortReplyList(replyList);

		// Total row number depends on the replies returned from server
		int totalRows = replyList.size();
		// Initial current page at page 1
		int nowPage = 1;
		// Get page numbers
		int totalPage = getTotalPage(pageSize, totalRows);

		/**
		 * Add associated topics to current page
		 */
		if (totalRows >= nowPage * pageSize) {
			for (int i = nowPage - 1; i < nowPage * pageSize; i++) {
				repliesOnCurrentPage.add(replyList.get(i));
			}
		} else {
			for (int i = nowPage - 1; i < totalRows; i++) {
				repliesOnCurrentPage.add(replyList.get(i));
			}
		}
		// Set all the conditions to request because we still need them on
		// page

		request.setAttribute("totalPage", nowPage + "/" + totalPage);
		request.setAttribute("nowPage", nowPage);
		request.setAttribute("replyList", repliesOnCurrentPage);
		request.setAttribute("topic", topic);
		request.setAttribute("totalPageNum", totalPage);
		request.setAttribute("statusMap", getStatusMap());
		request.setAttribute("topicId", topicId);
		return mapping.findForward("succ");
	}

	public ActionForward postReply(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		int topicId = Integer.valueOf(request.getParameter("topicId"));
		Topic topic = topicService.getTopicById(topicId);
		User author = userService.getUserById(topic.getAuthor().getId());
		Reply newReply = new Reply();
		newReply.setSubject(request.getParameter("replySubject"));
		newReply.setContent(request.getParameter("replyContent"));
		newReply.setStatus(Constants.REPLY_ACTIVE);
		replyService.createReply(newReply, author, topic);
		// This list stored all the topics queried from database
		Set<Reply> replySet = topic.getReplies();
		List<Reply> replyList = new ArrayList<Reply>();
		for (Reply reply : replySet) {
			replyList.add(reply);
		}
		List<Reply> repliesOnCurrentPage = new ArrayList<Reply>();
		sortReplyList(replyList);

		// Total row number depends on the replies returned from server
		int totalRows = replyList.size();
		// Initial current page at page 1
		int nowPage = 1;
		// Get page numbers
		int totalPage = getTotalPage(pageSize, totalRows);

		/**
		 * Add associated topics to current page
		 */
		if (totalRows >= nowPage * pageSize) {
			for (int i = nowPage - 1; i < nowPage * pageSize; i++) {
				repliesOnCurrentPage.add(replyList.get(i));
			}
		} else {
			for (int i = nowPage - 1; i < totalRows; i++) {
				repliesOnCurrentPage.add(replyList.get(i));
			}
		}
		// Set all the conditions to request because we still need them on
		// page

		request.setAttribute("totalPage", nowPage + "/" + totalPage);
		request.setAttribute("nowPage", nowPage);
		request.setAttribute("replyList", repliesOnCurrentPage);
		request.setAttribute("topic", topic);
		request.setAttribute("totalPageNum", totalPage);
		request.setAttribute("statusMap", getStatusMap());
		request.setAttribute("topicId", topicId);
		return mapping.findForward("succ");
	}

	public HashMap<String, String> getStatusMap() {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("0", "Yes");
		map.put("1", "No");
		return map;
	}

	// Go to Next Page
	public ActionForward goToNextPage(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		int topicId = Integer.valueOf(request.getParameter("topicId"));
		Topic topic = topicService.getTopicById(topicId);
		// This list stored all the topics queried from database
		Set<Reply> replySet = topic.getReplies();
		List<Reply> replyList = new ArrayList<Reply>();
		for (Reply reply : replySet) {
			replyList.add(reply);
		}
		List<Reply> repliesOnCurrentPage = new ArrayList<Reply>();
		sortReplyList(replyList);
		int totalRows = replyList.size();
		ShowTopicDetailsForm tf = (ShowTopicDetailsForm) form;
		int nowPage = tf.getNowPage();
		int totalPage = getTotalPage(pageSize, totalRows);

		if (totalRows > (nowPage + 1) * pageSize) {
			for (int i = nowPage * pageSize; i < (nowPage + 1) * pageSize; i++) {
				repliesOnCurrentPage.add(replyList.get(i));
			}
		} else {
			for (int i = nowPage * pageSize; i < totalRows; i++) {
				repliesOnCurrentPage.add(replyList.get(i));
			}
		}
		nowPage = nowPage + 1;
		// Set all the conditions to request because we still need them on
		// page

		request.setAttribute("totalPage", nowPage + "/" + totalPage);
		request.setAttribute("nowPage", nowPage);
		request.setAttribute("replyList", repliesOnCurrentPage);
		request.setAttribute("topic", topic);
		request.setAttribute("totalPageNum", totalPage);
		request.setAttribute("statusMap", getStatusMap());
		request.setAttribute("topicId", topicId);
		return mapping.findForward("succ");
	}

	// Go to Previous Page
	public ActionForward goToPreviousPage(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		int topicId = Integer.valueOf(request.getParameter("topicId"));
		Topic topic = topicService.getTopicById(topicId);
		// This list stored all the topics queried from database
		Set<Reply> replySet = topic.getReplies();
		List<Reply> replyList = new ArrayList<Reply>();
		for (Reply reply : replySet) {
			replyList.add(reply);
		}
		List<Reply> repliesOnCurrentPage = new ArrayList<Reply>();
		sortReplyList(replyList);
		int totalRows = replyList.size();
		ShowTopicDetailsForm tf = (ShowTopicDetailsForm) form;
		int nowPage = tf.getNowPage();
		int totalPage = getTotalPage(pageSize, totalRows);

		if (nowPage - 2 >= 0) {
			for (int i = (nowPage - 2) * pageSize; i < (nowPage - 1) * pageSize; i++) {
				repliesOnCurrentPage.add(replyList.get(i));
			}
		}
		nowPage = nowPage - 1;
		// Set all the conditions to request because we still need them on
		// page

		request.setAttribute("totalPage", nowPage + "/" + totalPage);
		request.setAttribute("nowPage", nowPage);
		request.setAttribute("replyList", repliesOnCurrentPage);
		request.setAttribute("topic", topic);
		request.setAttribute("totalPageNum", totalPage);
		request.setAttribute("statusMap", getStatusMap());
		request.setAttribute("topicId", topicId);
		return mapping.findForward("succ");
	}

	// Go to Target Page
	public ActionForward goToTargetPage(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int topicId = Integer.valueOf(request.getParameter("topicId"));
		Topic topic = topicService.getTopicById(topicId);
		// This list stored all the topics queried from database
		Set<Reply> replySet = topic.getReplies();
		List<Reply> replyList = new ArrayList<Reply>();
		for (Reply reply : replySet) {
			replyList.add(reply);
		}
		List<Reply> repliesOnCurrentPage = new ArrayList<Reply>();
		sortReplyList(replyList);
		int totalRows = replyList.size();

		ShowTopicDetailsForm tf = (ShowTopicDetailsForm) form;
		int nowPage = tf.getNowPage();
		int totalPage = getTotalPage(pageSize, totalRows);
		if (nowPage > 0 && nowPage <= totalPage) {
			repliesOnCurrentPage = getTargetPageForums(replyList, nowPage,
					totalRows);
		}

		// Set all the conditions to request because we still need them on
		// page

		request.setAttribute("totalPage", nowPage + "/" + totalPage);
		request.setAttribute("nowPage", nowPage);
		request.setAttribute("replyList", repliesOnCurrentPage);
		request.setAttribute("topic", topic);
		request.setAttribute("totalPageNum", totalPage);
		request.setAttribute("statusMap", getStatusMap());
		request.setAttribute("topicId", topicId);
		return mapping.findForward("succ");
	}

	// Get topics on target page, This method is much useful
	public List<Reply> getTargetPageForums(List<Reply> list, int targetNum,
			int totalNum) {
		List<Reply> data = new ArrayList<Reply>();
		if (targetNum * pageSize <= totalNum) {
			for (int i = (targetNum - 1) * pageSize; i < (targetNum * pageSize); i++) {
				data.add(list.get(i));
			}
		} else {
			for (int i = (targetNum - 1) * pageSize; i < totalNum; i++) {
				data.add(list.get(i));
			}
		}
		return data;
	}

	public int getTotalPage(int pageSize, int totalRows) {
		int totalPage;
		if (totalRows % pageSize > 0) {
			totalPage = totalRows / pageSize + 1;
		} else {
			totalPage = totalRows / pageSize;
		}
		return totalPage;
	}

}
